package com.binarysearch;

public class WoodCut {
    public static void main(String[] args) {
        int[] L = {232, 124, 456};
        int k = 7;
        System.out.println(woodCut(L, k));
//        int[] L2 = {1, 2, 3};
//        System.out.println(woodCut(L2, k));
    }

    public static int woodCut(int[] L, int k) {
        if (L == null || L.length == 0) return 0;
        if (k <= 0) return k;

        int left = 1;
        int right = 0;
        for (int length : L)
            right = Math.max(right, length);
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (count(L, mid) >= k) {
                left = mid;
            } else {
                right = mid;
            }
        }
        if (count(L, left) >= k)
            return left;
        if (count(L, right) >= k)
            return right;
        return 0;
    }


    public static int count(int[] L, int k) {
        int pieces = 0;
        for (int len : L) {
            pieces += len / k;
        }
        return pieces;
    }



    /*public static int woodCut(int[] L, int k) {
        if (L == null || L.length == 0) return 0;
        if (k <= 0) return 0;

        int left = 1;
        int right = 0;
        for (int length : L) {
            right = Math.max(right, length);
        }

        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (count(L, mid) >= k) {
                left = mid;
            } else
                right = mid;
        }
        System.out.println(left);
        System.out.println(right);
        if (count(L, right) >= k)
            return right;

        if (count(L, left) >= k)
            return left;

        return 0;
    }

    private static int count(int[] L, int length) {
        int pieces = 0;
        for (int l : L) {
            pieces += l / length;
        }
        return pieces;
    }*/
}
